#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一API配置管理器
所有脚本都通过这个管理器获取API配置，确保一致性
"""

import json
import os
from typing import Dict, Optional, List
from dataclasses import dataclass


@dataclass
class APIConfig:
    """API配置信息"""
    name: str
    api_key: str
    secret_key: Optional[str] = None
    model: str = ""
    enabled: bool = True
    display_name: str = ""


class UnifiedAPIManager:
    """统一API配置管理器"""
    
    def __init__(self, config_file: str = "config.json"):
        self.config_file = config_file
        self.config = {}
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        if not os.path.exists(self.config_file):
            print(f"❌ 配置文件 {self.config_file} 不存在")
            return False
        
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                self.config = json.load(f)
            return True
        except Exception as e:
            print(f"❌ 配置文件加载失败: {e}")
            return False
    
    def get_api_config(self, service_name: str) -> Optional[APIConfig]:
        """获取指定服务的API配置"""
        ai_services = self.config.get("ai_services", {})
        service_config = ai_services.get(service_name, {})
        
        if not service_config.get("enabled", True):
            return None
        
        api_key = service_config.get("api_key", "")
        
        # 过滤占位符值
        placeholder_values = [
            "your_api_key",
            "test_key", 
            f"your_{service_name}_api_key",
            f"test_{service_name}_key",
            "your_" + service_name.replace("_", "") + "_api_key",
            # 额外的占位符模式
            "your_baidu_api_key",
            "your_baidu_secret_key", 
            "your_zhipu_api_key",
            "your_aliyun_api_key",
            "your_deepseek_api_key",
            "your_kimi_api_key"
        ]
        
        # 检查是否以占位符开头或在占位符列表中
        if not api_key or api_key in placeholder_values or api_key.startswith("your_") or api_key.startswith("test_"):
            return None
        
        return APIConfig(
            name=service_name,
            api_key=api_key,
            secret_key=service_config.get("secret_key"),
            model=service_config.get("model", ""),
            enabled=service_config.get("enabled", True),
            display_name=service_config.get("display_name", service_name)
        )
    
    def get_all_valid_apis(self) -> Dict[str, APIConfig]:
        """获取所有有效的API配置"""
        valid_apis = {}
        ai_services = self.config.get("ai_services", {})
        
        for service_name in ai_services.keys():
            api_config = self.get_api_config(service_name)
            if api_config:
                valid_apis[service_name] = api_config
        
        return valid_apis
    
    def get_deepseek_api_key(self) -> Optional[str]:
        """获取DeepSeek API密钥（兼容旧代码）"""
        deepseek_config = self.get_api_config("deepseek")
        return deepseek_config.api_key if deepseek_config else None
    
    def get_multi_ai_config(self) -> Dict[str, Dict]:
        """获取多AI对话模块需要的配置格式"""
        config = {}
        valid_apis = self.get_all_valid_apis()
        
        for service_name, api_config in valid_apis.items():
            if service_name == "baidu_ernie":
                if api_config.secret_key:
                    config["baidu"] = {
                        "api_key": api_config.api_key,
                        "secret_key": api_config.secret_key
                    }
            elif service_name == "aliyun_qwen":
                config["aliyun"] = {"api_key": api_config.api_key}
            elif service_name == "zhipu_glm":
                config["zhipu"] = {"api_key": api_config.api_key}
            elif service_name == "kimi":
                config["kimi"] = {"api_key": api_config.api_key}
            elif service_name == "deepseek":
                config["deepseek"] = {"api_key": api_config.api_key}
        
        return config
    
    def get_legacy_config(self) -> Dict:
        """获取完整配置（兼容旧代码）"""
        return self.config
    
    def print_api_status(self):
        """打印API配置状态"""
        print(f"\n{'='*60}")
        print(f"🔑 API配置状态")
        print(f"{'='*60}")
        
        valid_apis = self.get_all_valid_apis()
        
        if not valid_apis:
            print("❌ 没有配置任何有效的API服务")
            return
        
        print(f"✅ 已配置 {len(valid_apis)} 个有效的API服务:")
        
        for service_name, api_config in valid_apis.items():
            status = "🔑"
            key_preview = api_config.api_key[:10] + "..." if len(api_config.api_key) > 10 else api_config.api_key
            print(f"   {status} {api_config.display_name} ({service_name}): {key_preview}")
            if api_config.secret_key:
                secret_preview = api_config.secret_key[:10] + "..." if len(api_config.secret_key) > 10 else api_config.secret_key
                print(f"      🔐 Secret Key: {secret_preview}")
        
        # 检查未配置的服务
        ai_services = self.config.get("ai_services", {})
        unconfigured = []
        for service_name in ai_services.keys():
            if service_name not in valid_apis:
                unconfigured.append(service_name)
        
        if unconfigured:
            print(f"\n⚠️ 以下服务未正确配置:")
            for service_name in unconfigured:
                service_config = ai_services[service_name]
                reason = "已禁用" if not service_config.get("enabled", True) else "API密钥无效"
                print(f"   ❌ {service_config.get('display_name', service_name)} ({service_name}): {reason}")


# 全局实例
_api_manager = None

def get_api_manager() -> UnifiedAPIManager:
    """获取全局API管理器实例"""
    global _api_manager
    if _api_manager is None:
        _api_manager = UnifiedAPIManager()
    return _api_manager


def get_deepseek_api_key() -> Optional[str]:
    """获取DeepSeek API密钥的快捷函数"""
    return get_api_manager().get_deepseek_api_key()


def get_multi_ai_config() -> Dict[str, Dict]:
    """获取多AI配置的快捷函数"""
    return get_api_manager().get_multi_ai_config()


def get_all_valid_apis() -> Dict[str, APIConfig]:
    """获取所有有效API的快捷函数"""
    return get_api_manager().get_all_valid_apis()


def print_api_status():
    """打印API状态的快捷函数"""
    get_api_manager().print_api_status()


if __name__ == "__main__":
    # 测试脚本
    print("🔍 测试统一API配置管理器")
    manager = get_api_manager()
    manager.print_api_status()
    
    print(f"\n🔑 DeepSeek API: {get_deepseek_api_key()}")
    print(f"🤖 多AI配置: {list(get_multi_ai_config().keys())}") 